/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lyh.api.algorithm;

import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;

/**
 * @author SHOUSHEN.LUAN
 * @since 2023-10-26
 */
public class DateRangeAlgorithm implements StandardShardingAlgorithm<Comparable<? extends Date>> {

    public static int getQuarter(LocalDate date) {
        int month = date.getMonthValue();
        if (month >= 1 && month <= 3) {
            return 1;
        } else if (month >= 4 && month <= 6) {
            return 2;
        } else if (month >= 7 && month <= 9) {
            return 3;
        } else {
            return 4;
        }
    }

    @Override
    public String doSharding(Collection<String> availableTargetNames,
                             PreciseShardingValue<Comparable<? extends Date>> shardingValue) {
        System.out.println("订单拆分历史表处理:" + Arrays.toString(availableTargetNames.toArray()));
        Date date = (Date) shardingValue.getValue();
        LocalDate localDate = Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
        int quarter = getQuarter(localDate);
        int year = localDate.getYear();
        for (String availableTargetName : availableTargetNames) {
            if (availableTargetName.endsWith(String.valueOf("_" + year) + quarter)) {
                return availableTargetName;
            }
        }
        throw new IllegalStateException("路由失败");
    }

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames,
                                         RangeShardingValue<Comparable<? extends Date>> shardingValue) {
        return availableTargetNames;
    }

    @Override
    public String getType() {
        return "CUSTOM_DATE_RANGE";
    }
}
